<template>
  <uni-popup ref="datePopup" type="bottom">
    <view class="picker-wrapper">
      <view class="picker-header">
        <text @click="handleCancel">取消</text>
        <text>{{ title }}</text>
        <text @click="handleConfirm">确定</text>
      </view>
      <picker-view
        class="picker-view"
        :indicator-style="indicatorStyle"
        :value="dateTimeIndex"
        @change="onDateTimeChange"
      >
        <picker-view-column>
          <view class="picker-item" v-for="year in years" :key="year">{{ year }}年</view>
        </picker-view-column>
        <picker-view-column>
          <view class="picker-item" v-for="month in months" :key="month">{{ month }}月</view>
        </picker-view-column>
        <picker-view-column>
          <view class="picker-item" v-for="day in days" :key="day">{{ day }}日</view>
        </picker-view-column>
        <picker-view-column>
          <view class="picker-item" v-for="hour in hours" :key="hour">{{ hour }}时</view>
        </picker-view-column>
      </picker-view>
    </view>
  </uni-popup>
</template>

<script setup>
import { ref, onMounted,watch } from 'vue'

const props = defineProps({
  title: {
    type: String,
    default: '选择日期时间'
  },
  value: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:value', 'confirm', 'cancel'])

const datePopup = ref(null)
const indicatorStyle = 'height: 88rpx;'

// 生成时间数据
const now = new Date()
const years = Array.from({length: 100}, (_, i) => now.getFullYear() + i)
const months = Array.from({length: 12}, (_, i) => i + 1)
const hours = Array.from({length: 24}, (_, i) => i)

// 获取当前日期的索引
const getCurrentDateIndex = () => {
  const currentDate = new Date()
  const yearIndex = years.findIndex(year => year === currentDate.getFullYear())
  const monthIndex = currentDate.getMonth()
  const dayIndex = currentDate.getDate() - 1
  const hourIndex = currentDate.getHours()
  return [yearIndex, monthIndex, dayIndex, hourIndex]
}

// 初始化选择器索引
const dateTimeIndex = ref(getCurrentDateIndex())

// 根据年月获取当月天数
const getDaysInMonth = (year, month) => {
  return new Date(year, month, 0).getDate()
}

// 生成天数数组
const generateDays = (year, month) => {
  const daysCount = getDaysInMonth(year, month)
  return Array.from({length: daysCount}, (_, i) => i + 1)
}

// 初始化days数组
const days = ref(generateDays(years[dateTimeIndex.value[0]], months[dateTimeIndex.value[1]] - 1))

// 从日期字符串设置选择器索引
const setDateTimeIndexFromString = (dateString) => {
  const matches = dateString.match(/(\d{4})年(\d{1,2})月(\d{1,2})日\s+(\d{1,2}):00/)
  if (matches) {
    const [_, year, month, day, hour] = matches
    const yearIndex = years.findIndex(y => y === parseInt(year))
    const monthIndex = parseInt(month) - 1
    const dayIndex = parseInt(day) - 1
    const hourIndex = parseInt(hour)
    dateTimeIndex.value = [yearIndex, monthIndex, dayIndex, hourIndex]
    days.value = generateDays(parseInt(year), parseInt(month))
  }
}

// 日期选择变化
const onDateTimeChange = (e) => {
  const newValue = e.detail.value
  if (newValue[0] !== dateTimeIndex.value[0] || newValue[1] !== dateTimeIndex.value[1]) {
    const selectedYear = years[newValue[0]]
    const selectedMonth = months[newValue[1]]
    days.value = generateDays(selectedYear, selectedMonth)
    
    if (newValue[2] >= days.value.length) {
      newValue[2] = days.value.length - 1
    }
  }
  dateTimeIndex.value = newValue
}

// 格式化日期
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  return `${year}年${month}月${day}日 ${hour}:00`
}

// 确认选择
const handleConfirm = () => {
  const [yearIdx, monthIdx, dayIdx, hourIdx] = dateTimeIndex.value
  const selectedDate = new Date(
    years[yearIdx],
    monthIdx,
    days.value[dayIdx],
    hours[hourIdx]
  )
  
  const formattedDate = formatDate(selectedDate)
  emit('update:value', formattedDate)
  emit('confirm', formattedDate)
  datePopup.value.close()
}

// 取消选择
const handleCancel = () => {
  emit('cancel')
  datePopup.value.close()
}

// 监听 value 的变化
watch(() => props.value, (newValue) => {
  if (newValue) {
    setDateTimeIndexFromString(newValue)
  } else {
    // 如果没有值，使用当前时间
    dateTimeIndex.value = getCurrentDateIndex()
    days.value = generateDays(years[dateTimeIndex.value[0]], months[dateTimeIndex.value[1]] - 1)
  }
}, { immediate: true })


// 对外暴露的方法
defineExpose({
  open: () => {
    datePopup.value.open()
  },
  close: () => datePopup.value.close()
})
</script>

<style lang="scss" scoped>
.picker-wrapper {
  background: #FFFFFF;
  border-radius: 24rpx 24rpx 0 0;
}

.picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #EEEEEE;
  
  text {
    font-size: 28rpx;
    
    &:first-child {
      color: #999999;
    }
    
    &:last-child {
      color: #1890FF;
    }
  }
}

.picker-view {
  width: 100%;
  height: 480rpx;
}

.picker-item {
  line-height: 88rpx;
  text-align: center;
  font-size: 28rpx;
}
</style> 